﻿using System;
using System.Web;

namespace DuJianliang.ApplicationPlatform.Common
{
    public class UnhandledExceptionModule : IHttpModule
    {
        static object syncObj = new object();
        static bool isInit = false;

        #region IHttpModule 成员

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            lock (syncObj)
            {
                if (!isInit)
                {
                    context.Error += new EventHandler(context_Error);
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                    isInit = true;
                }
            }
        }

        void context_Error(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            Exception ex = httpApplication.Server.GetLastError();
            if (ex == null) return;

            ex = ex.GetBaseException();
            Helper.Instance.SetException(ex);
            httpApplication.Server.ClearError();
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            Helper.Instance.SetException(ex);     
        }

        #endregion
    }
}